package com.aust.demo02;

import java.util.concurrent.*;

/**
 * 多个线程操作一份资源
 */
public class TestCallableMO implements Callable<Boolean> {

    // 票数
    private int ticketNums = 10;

    @Override
    public Boolean call() throws Exception {
        while (ticketNums >= 0) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums-- + "张票");
        }
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 创建任务
         */
        TestCallableMO testCallableMO = new TestCallableMO();
        /**
         * 创建执行服务
         */
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        /**
         * 提交服务
         */
        Future<Boolean> s1 = executorService.submit(testCallableMO);
        Future<Boolean> s2 = executorService.submit(testCallableMO);
        Future<Boolean> s3 = executorService.submit(testCallableMO);
        /**
         * 获取结果
         */
        Boolean r1 = s1.get();
        Boolean r2 = s2.get();
        Boolean r3 = s3.get();
        System.out.println(r1);
        System.out.println(r2);
        System.out.println(r3);
        /**
         * 关闭服务
         */
        executorService.shutdown();
    }

}
